﻿using DatabaseInvoke;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using TSC;

namespace TSC
{

    public class TempratureManager
    {
        private SensorCable sensorCable1;
        private SensorCable sensorCable2;
        System.Timers.Timer timer;
        private TempratureSQL tempSQL;
        private bool firstStart;

        public TempratureManager()
        {
            //
            sensorCable1 = new SensorCable(1);
            sensorCable2 = new SensorCable(2);
            //
            timer = new System.Timers.Timer(30000);
            timer.Elapsed += Timer_Elapsed;
            timer.AutoReset = true;   //设置是执行一次（false）还是一直执行(true)；  
            //
            tempSQL = new TempratureSQL();
            //
        }

        public async Task Run(CancellationToken token)
        {
            //
            timer.Enabled = true;     //是否执行System.Timers.Timer.Elapsed事件；   

            while (!token.IsCancellationRequested)
            {
                //检查Cable1连接状态
                if (!sensorCable1.ConnState)
                {
                    Task.Run(() => sensorCable1.Connect());
                }

                if (!sensorCable2.ConnState)
                {
                    Task.Run(() => sensorCable2.Connect());
                }

                await Task.Delay(5000);

                if (!firstStart)
                {
                    firstStart = true;
                    Timer_Elapsed(null, null);
                }
            }
            Task.Run(() => CloseAll());
        }

        private async Task CloseAll()
        {
            timer.Enabled = false;
            Task.Run(() => sensorCable1.Close());
            Task.Run(() => sensorCable1.Close());
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            List<TempratureModel> lstTemp = new List<TempratureModel>();
            //
            //在这里需要轮训读取2个
            for (int i = 1; i < 35; i++)
            {
                TempratureModel model = ReadTemptature(i);
                if (model != null)
                    lstTemp.Add(model);
            }

            if (lstTemp.Any())
            {
                tempSQL.BulkUpdateTemprature(lstTemp);
            }
        }

        private TempratureModel ReadTemptature(int cabelId)
        {
            short[] result = new short[15];
            bool success = false;
            if (cabelId <= 16)
            {
                success = sensorCable1.ReadTemprature(cabelId, out result);
            }
            else
            {
                success = sensorCable2.ReadTemprature(cabelId, out result);
            }

            if (success)
            {
                double average = ComputeAverage(result, out short max);
                return new TempratureModel(cabelId, average, max);
            }
            else
                return null;
        }

        private double ComputeAverage(short[] result, out short max)
        {
            max = 0;
            if (result.Any())
                {
                double acc = 0d;
                foreach (short num in result)
                {
                    acc += num;
                    if (max < num)
                        max = num;
                }
                return acc / result.Length;
            }
            return 0;
        }
    }
}
